<template>
  <div class="mindmap-editor">
    <div ref="container" class="mindmap-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { Graph as X6Graph, Node } from '@antv/x6';
import { Selection } from '@antv/x6-plugin-selection';

// 扩展Graph接口，添加缺失的方法类型定义
interface Graph extends X6Graph {
  registerNode(name: string, definition: any, override?: boolean): this;
  registerEdge(name: string, definition: any, override?: boolean): this;
  getSelectedNodes(): Node[];
  removeNodes(nodes: Node[] | string[]): this;
}

const graph = ref<Graph | null>(null);
const container = ref<HTMLDivElement | null>(null);

// 节点数据类型
interface NodeData {
  id: string;
  x: number;
  y: number;
  width: number;
  height: number;
  shape: 'rect' | 'circle' | 'ellipse' | 'polygon';
  text: string;
  fillColor: string;
  strokeColor: string;
}

// 边数据类型
interface EdgeData {
  id: string;
  source: string;
  target: string;
  label: string;
  strokeColor: string;
}

// 初始化画布
const initGraph = () => {
  if (!container.value) return;

  // 类型断言为扩展后的Graph接口
  graph.value = new X6Graph({
    container: container.value,
    width: container.value.clientWidth,
    height: container.value.clientHeight,
    grid: { visible: true, size: 10 },
    panning: { enabled: true, modifiers: ['alt'] },
    mousewheel: {
      enabled: true,
      modifiers: ['ctrl'],
      factor: 1.2,
      maxScale: 3,
      minScale: 0.5,
    },
    connecting: {
      router: 'manhattan',
      connector: 'rounded',
      allowBlank: false,
      snap: true,
      highlight: true,
    },
  }) as Graph;

  // 启用选择插件
  graph.value.use(new Selection({ rubberband: true }));

  // 注册自定义节点（支持编辑工具）
  graph.value.registerNode('custom-node', {
    inherit: 'rect',
    markup: [
      { tagName: 'rect', selector: 'body' },
      { tagName: 'text', selector: 'label' },
    ],
    attrs: {
      body: {
        strokeWidth: 1,
        fill: '#EFF4FF',
        stroke: '#5F95FF',
      },
      label: {
        textAnchor: 'middle',
        dominantBaseline: 'middle',
        fill: '#262626',
        fontSize: 14,
      },
    },
    tools: [
      {
        name: 'node-editor',
        args: {
          attrs: {
            backgroundColor: '#FFFFFF',
            border: '1px solid #5F95FF',
            padding: '4px 8px',
            borderRadius: 4,
          },
          autoFocus: true,
        },
      },
    ],
    shape: (node: Node) => {
      const shape = node.data.shape || 'rect';
      if (shape === 'circle') return 'circle';
      if (shape === 'ellipse') return 'ellipse';
      if (shape === 'polygon') return 'polygon';
      return 'rect';
    },
  });

  // 注册自定义边（支持编辑工具）
  graph.value.registerEdge('custom-edge', {
    inherit: 'edge',
    markup: [
      { tagName: 'path', selector: 'line' },
      { tagName: 'text', selector: 'label' },
    ],
    attrs: {
      line: {
        strokeWidth: 2,
        stroke: '#A2B1C3',
      },
      label: {
        textAnchor: 'middle',
        dominantBaseline: 'middle',
        fill: '#595959',
        fontSize: 12,
      },
    },
    tools: [
      {
        name: 'edge-editor',
        args: {
          attrs: {
            backgroundColor: '#FFFFFF',
            border: '1px solid #5F95FF',
            padding: '2px 6px',
            borderRadius: 3,
          },
        },
      },
    ],
  });
};

// 添加节点
const addNode = (
  type: NodeData['shape'] = 'rect',
  x: number = 100,
  y: number = 100
): Node => {
  if (!graph.value) throw new Error('Graph not initialized');

  const id = `node-${Date.now()}`;
  const defaultProps: Omit<NodeData, 'id'> = {
    x,
    y,
    width: type === 'circle' ? 60 : 100,
    height: type === 'circle' ? 60 : 40,
    shape: type,
    text: '新节点',
    fillColor: type === 'circle' ? '#f6ffed' : '#EFF4FF',
    strokeColor: type === 'circle' ? '#52c41a' : '#5F95FF',
  };

  const node = graph.value.addNode({
    id,
    shape: 'custom-node',
    data: defaultProps,
    attrs: {
      body: {
        fill: defaultProps.fillColor,
        stroke: defaultProps.strokeColor,
        ...(type === 'circle' ? { rx: 30, ry: 30 } : {}),
        ...(type === 'polygon' ? { points: '30,0 60,30 30,60 0,30' } : {}),
      },
      label: {
        text: defaultProps.text,
      },
    },
  });

  if (type === 'ellipse') {
    (node as any).setWidth(120);
    (node as any).setHeight(60);
  }

  return node;
};

// 添加边
const addEdge = (sourceId: string, targetId: string, label = '关系') => {
  if (!graph.value) return;
  
  const edgeId = `edge-${Date.now()}`;
  graph.value.addEdge({
    id: edgeId,
    shape: 'custom-edge',
    source: sourceId,
    target: targetId,
    data: { label, strokeColor: '#A2B1C3' },
    attrs: {
      line: {
        stroke: '#A2B1C3',
      },
      label: {
        text: label,
      },
    },
  });
};

// 删除选中元素
const deleteSelected = () => {
  if (!graph.value) return;
  const selectedCells = graph.value.getSelectedCells();
  graph.value.removeCells(selectedCells);
};

// 加载数据
const loadData = (data: { nodes: NodeData[]; edges: EdgeData[] }) => {
  if (!graph.value) return;
  graph.value.fromJSON({ cells: [...data.nodes, ...data.edges] });
  graph.value.centerContent();
};

// 导出数据
const exportData = (): { nodes: NodeData[]; edges: EdgeData[] } | null => {
  if (!graph.value) return null;
  const cells = graph.value.toJSON().cells;
  return {
    nodes: cells.filter(cell => cell.shape) as unknown as NodeData[],
    edges: cells.filter(cell => cell.shape === 'custom-edge') as unknown as EdgeData[],
  };
};

// 生命周期钩子
onMounted(() => {
  initGraph();
  try {
    // 示例数据
    const node1 = addNode('rect', 180, 60);
    const node2 = addNode('circle', 320, 250);
    if (node1 && node2) {
      addEdge(node1.id as string, node2.id as string, '关联');
    }
  } catch (error) {
    console.error('Failed to initialize example nodes:', error);
  }
});

onBeforeUnmount(() => {
  graph.value?.dispose();
});

// 暴露方法
defineExpose({
  addNode,
  addEdge,
  deleteSelected,
  loadData,
  exportData,
});
</script>

<style scoped>
.mindmap-editor {
  width: 100%;
  height: 800px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.mindmap-container {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  overflow: auto;
}

/* 节点编辑器样式 */
.x6-tool-node-editor {
  font-family: 'Segoe UI', sans-serif;
  font-size: 14px;
  color: #262626;
  min-width: 40px;
  text-align: center;
  transition: border-color 0.2s;
}

.x6-tool-node-editor:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 边编辑器样式 */
.x6-tool-edge-editor {
  font-size: 12px;
  color: #595959;
  background-color: #f8fafc;
  border-color: #d0d7de;
}

.x6-tool-edge-editor:focus {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

/* 边标签样式 */
.x6-edge .label {
  pointer-events: none;
  user-select: none;
}
</style>